/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
 */

package com.example.questionnaire;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebView;
import android.widget.LinearLayout;

import com.example.questionnaire.event.GotoScreensaverEvent;
import com.example.questionnaire.event.ScreenActionEvent;
import com.example.questionnaire.event.StopScreensaverEvent;
import com.example.questionnaire.service.ScreenActionService;
import com.example.questionnaire.utils.GbssUtils;
import com.example.questionnaire.utils.PrefUtils;
import com.example.questionnaire.utils.StringUtils;
import com.example.questionnaire.utils.UDPUtils;

import org.apache.cordova.*;
import org.apache.cordova.common.CommonPlugin;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainActivity extends CordovaActivity {

    private View mWelcomeView;
    private int screensaverNum;
    private int recLen = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        mWelcomeView = LayoutInflater.from(this).inflate(R.layout.activity_welcome, null);
        String params = "?" + PrefUtils.getString(CommonPlugin.PARAMS, "");
//        params = "factory=2&forfloor=3&fromSource=1";
        // Set by <content src="index.html" /> in config.xml
        loadUrl(launchUrl + params, mWelcomeView);
        initView();
        UDPUtils.sendMessage("A", 1);

        Intent intent = new Intent(this, ScreenActionService.class);
        startService(intent);

        initListener();
        initReceiver();
    }

    private void initListener() {
        GbssUtils.getInstance().observeSoftKeyboard(this, new GbssUtils.OnSoftKeyboardChangeListener() {

            @Override
            public void onSoftKeyBoardChange(int softKeybardHeight, boolean visible) {
                if (visible) {
                    handler.removeCallbacksAndMessages(null);
                } else {
                    reckonTime();
                }
            }
        });
    }

    private void initReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(NetworkConnectChangedReceiver, filter);
    }

    private void initView() {
        LinearLayout llyContainer = (LinearLayout) mWelcomeView.findViewById(R.id.lly_container);
        llyContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showWebView();
            }
        });

        appView.getView().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        recLen = 0;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        recLen = 0;
                        break;
                    case MotionEvent.ACTION_UP:
                        recLen = 0;
                        break;
                }
                return false;
            }
        });
    }

    private void showWebView() {
        mWelcomeView.setVisibility(View.GONE);
        UDPUtils.sendMessage("B", 1);
        reckonTime();
    }

    /**
     * 这里监听屏幕锁屏
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onScreenAction(ScreenActionEvent event) {
        if (!StringUtils.isEmpty(event.getScreenAction())) {
            if (Intent.ACTION_SCREEN_OFF.equals(event.getScreenAction().trim())) {
                //这里设置显示 欢迎界面
                finish();
            }
        }
    }

    /**
     * 这里监听saveSetupInformation与gotoScreensaver这两个action之后的操作
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showWelcomeView(GotoScreensaverEvent event) {
        if (event.isShowScreenSave()) {
            handler.removeCallbacksAndMessages(null);
            mWelcomeView.setVisibility(View.VISIBLE);
            UDPUtils.sendMessage("A", 1);
        }
        String params = "?" + PrefUtils.getString(CommonPlugin.PARAMS, "");
        loadUrlandReload(launchUrl + params);
        if (!event.isShowScreenSave()) {
            reckonTime();
        }
    }

    /**
     * 这里监听stopScreensaver这个action之后的操作
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void stopScreensaver(StopScreensaverEvent event) {
        handler.removeCallbacksAndMessages(null);
    }

    private void reckonTime() {
        handler.removeCallbacksAndMessages(null);
        String screensaver = PrefUtils.getString(CommonPlugin.SCREENSAVER, "");
        if (!StringUtils.isEmpty(screensaver)) {
            if (screensaver.contains("S")) {
                screensaverNum = Integer.valueOf(screensaver.replace("S", "").trim());
            } else {
                screensaverNum = Integer.valueOf(screensaver.replace("s", "").trim());
            }
            recLen = 0;
            handler.postDelayed(runnable, 1000);
        }
    }

    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (recLen < screensaverNum) {
                recLen++;
                handler.postDelayed(this, 1000);
            } else {
                handler.removeCallbacksAndMessages(null);
                mWelcomeView.setVisibility(View.VISIBLE);
                UDPUtils.sendMessage("A", 1);
                String params = "?" + PrefUtils.getString(CommonPlugin.PARAMS, "");
                loadUrlandReload(launchUrl + params);
            }
        }
    };

    @Override
    protected void onStop() {
        super.onStop();
        MyApplication.application.setStartOver(false);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unregisterReceiver(NetworkConnectChangedReceiver);
        handler.removeCallbacksAndMessages(null);
    }

    private BroadcastReceiver NetworkConnectChangedReceiver = new BroadcastReceiver() {
        private boolean isFirst = true;

        @Override
        public void onReceive(Context context, Intent intent) {
            if (isFirst) {
                isFirst = false;
                return;
            }
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                ConnectivityManager systemService = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo info = systemService.getActiveNetworkInfo();
                if (info != null && info.isAvailable()) {
                    //有网络
                    String params = "?" + PrefUtils.getString(CommonPlugin.PARAMS, "");
                    loadUrlandReload(launchUrl + params);
                } else {
                    loadUrlandReload(launchUrl);
                }
                reckonTime();
            }
        }
    };

    private void loadUrlandReload(String url) {
        appView.loadUrl(url);
    }
}
